<template>
  <div class="content-wrapper">

    <div class="content-container">
      <el-form label-width="auto" :inline="true" class="demo-form-inline">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="配送单号" class="full-width">
              <el-input v-model="filters.deliveryId" placeholder="请输入配送单号" class="full-width"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="出发地" class="full-width">
              <el-input v-model="filters.origin" placeholder="请输入出发地" class="full-width"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="车辆" class="full-width">
              <el-input v-model="filters.vehicleNumber" placeholder="请输入车辆编号" class="full-width"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="类型" class="full-width">
              <el-select v-model="filters.deliveryType" placeholder="请选择类型" class="full-width">
                <el-option label="全部" :value="null"></el-option>
                <el-option label="城内" :value="'城内'"></el-option>
                <el-option label="城际" :value="'城际'"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
<!--          <el-col :span="6">-->
<!--            <el-form-item label="状态" class="full-width">-->
<!--              <el-select v-model="filters.state" placeholder="请选择状态" class="full-width">-->
<!--                <el-option label="全部" :value="null"></el-option>-->
<!--                <el-option label="待发货" :value="0"></el-option>-->
<!--                <el-option label="配送中" :value="1"></el-option>-->
<!--                <el-option label="已送达" :value="2"></el-option>-->
<!--              </el-select>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
          <el-col :span="8">
            <el-form-item label="创建时间" class="full-width">
              <el-date-picker
                  v-model="filters.generatedDate"
                  type="daterange"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  class="full-width">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item class="right full-width" label=" ">
              <el-button-group class="full-width">
                <el-button icon="search" type="primary" plain @click="search" style="width: 50%">查询</el-button>
                <el-button icon="refresh" @click="resetFilters" style="width: 50%">重置</el-button>
              </el-button-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="divider"></div>
      <el-table
          :data="currentTableData"
          style="width: 100%; flex: 1"
          :header-cell-style="{
                  backgroundColor: '#f5f7fa',
                  color: '#333',
                  fontWeight: 'bold',
                  textAlign: 'center',
                  padding: '10px 0'
                }"
          :cell-style="{
                  padding: '10px 0'
                }"
          @selection-change="handleSelectionChange"
          row-key="deliveryBatchId">
        <el-table-column label="配送单ID" width="180" fixed>
          <template #default="{ row }">
            <template v-if="row.isFirst">
              <el-tooltip
                  effect="light"
                  placement="top"
                  :content="getDeliveryInfo(row.deliveryId)"
              >
                <el-button
                    type="text"
                    @click="toggleExpand(row.deliveryId)"
                >
                  {{ row.deliveryId }}
                </el-button>
              </el-tooltip>
            </template>
          </template>
        </el-table-column>
        <el-table-column prop="deliveryBatchId" label="批次号" width="130" fixed>
          <template v-slot="scope">
            <el-link type="primary" @click="openDetailDialog(scope.row.deliveryBatchId)">{{
                scope.row.deliveryBatchId
              }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="origin" label="出发地" width="160"></el-table-column>
        <el-table-column prop="deliveryType" label="配送类型" width="100"></el-table-column>
        <el-table-column label="批次重量" width="120" align="right">
          <template v-slot="scope">
            {{ scope.row.weight }}{{ scope.row.weightUnit }}
          </template>
        </el-table-column>
        <el-table-column prop="transportQuantity" label="运输数量" width="80" align="right"></el-table-column>
        <el-table-column prop="vehicleNumber" label="车辆" width="140"></el-table-column>
        <el-table-column prop="state" label="批次状态" width="140" align="center">
          <template v-slot="scope">
            <el-tag
                :type="scope.row.state === '待发货' ? 'danger' : scope.row.state === '配送中' ? 'warning' : 'success'"
                disable-transitions>
              {{ scope.row.state }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="generatedDate" label="创建时间" width="180">
          <template v-slot="scope">
            {{ formatDate(scope.row.generatedDate) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center">
          <template v-slot="scope">
            <el-button @click="openDialog(scope.row, true)" type="text" icon="EditPen" style="font-size: 13px">修改
            </el-button>
            <el-button @click="openLogisticDialog(scope.row.deliveryBatchId)" type="text" icon="Van"
                       style="font-size: 13px">
              追踪
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          background
          layout="total, prev, pager, next"
          :total="total"
          :page-size="pageSize"
          v-model:current-page="currentPage"
          @current-change="handleCurrentChange"
          class="fixed-pagination">
      </el-pagination>

      <!--    详情列表-->
      <delivery-detail-dialog
          v-model="detailDialogVisible"
          style="border-radius: 12px;
      justify-content: center;"
          :delivery-batch-id="selectedDelivery"/>

      <!--    物流信息页面-->
      <logistic-info-dialog
          :delivery-id="selectedDelivery"
          v-model="logisticDialogVisible"
          style="border-radius: 12px;
      justify-content: center;"
      />
    </div>
  </div>

  <el-dialog
      v-model="editDialogVisible"
      title="修改配送单"
      width="60%"
      @close="resetForm"
      style="border-radius: 12px;
      display: flex;
      flex-direction: column;
      margin: 0 !important;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      max-height: calc(100% - 30px);
      max-width: calc(100% - 30px);
      justify-content: center;"
  >
    <el-form v-model="form" label-width="100px">
      <el-form-item label="配送单号">
        <el-input v-model="form.deliveryBatchId" disabled/>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="form.state" placeholder="请选择状态">
          <el-option label="待发货" value="待发货"></el-option>
          <el-option label="配送中" value="配送中"></el-option>
          <el-option label="已送达" value="已送达"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="重量">
        <el-input-number v-model="form.weight" :min="0" step="0.1" placeholder="请输入重量"/>
      </el-form-item>
      <el-form-item label="重量单位">
        <el-input v-model="form.weightUnit" placeholder="请输入重量单位"/>
      </el-form-item>
      <el-form-item label="车辆编号">
        <el-input v-model="form.vehicleNumber" placeholder="请输入车辆编号"/>
      </el-form-item>
    </el-form>

    <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEdit">保存</el-button>
      </span>
  </el-dialog>
</template>

<script>
import {reactive, ref, onMounted} from "vue";
import {ElMessage} from "element-plus";
import {listDelivery, updateDelivery} from "@/api/delivery/delivery.js";
import DeliveryDetailDialog from "@/views/delivery/deliveryOrder/deliveryDetailDialog.vue";
import LogisticInfoDialog from "@/views/delivery/deliveryOrder/logisticInfoDialog.vue";

export default {
  components: {
    LogisticInfoDialog,
    DeliveryDetailDialog,
  },
  setup() {
    const filters = reactive({
      deliveryId: "",
      origin: "",
      deliveryType: null,
      generatedDate: [],
      state: null,
      vehicleNumber: "",
    });

    // 修改弹窗数据绑定
    const editDialogVisible = ref(false); // 控制弹窗的显示
    const form = reactive({
      deliveryId: '',
      state: null,
      weight: null,
      weightUnit: '',
      volume: null,
      volumeUnit: '',
      vehicleNumber: '',
    }); // 绑定表单数据

    const currentTableData = ref([]);
    const total = ref(0);
    const pageSize = ref(8);
    const currentPage = ref(1);
    const selectedDelivery = ref({});
    const rawData = ref([]);
    const expandedRows = ref([]); // 记录展开的配送单ID

    const search = async () => {
      const query = {
        deliveryId: filters.deliveryId,
        origin: filters.origin,
        state: filters.state,
        startDate: filters.generatedDate.length ? formatDate(filters.generatedDate[0]) : null,
        endDate: filters.generatedDate.length ? formatDate(filters.generatedDate[1]) : null,
        vehicleNumber: filters.vehicleNumber,
        deliveryType: filters.deliveryType,
        page: currentPage.value,
        pageSize: pageSize.value,
      };
      try {
        const response = await listDelivery(query);
        rawData.value = response.data;
        total.value = response.total;
        processTableData();
        console.log(currentTableData.value);
      } catch (error) {
        ElMessage.error("获取配送单信息失败");
        console.log(error);
      }
    };

    // 数据处理：将相同 deliveryId 的行分组，并标记首行
    const processTableData = () => {
      const batchData = [];
      rawData.value.forEach(order => {
        const isExpanded = expandedRows.value.includes(order.deliveryId);
        let isFirst = true;
        order.deliveryOrderBatchList.forEach(batch => {
          batchData.push({
            ...batch,
            deliveryId: order.deliveryId,
            isFirst,  // 标记首行
            visible: isFirst || isExpanded,
          });
          isFirst = false;  // 首行之后标记为false
        });
      });
      currentTableData.value = batchData;
    };


// 获取配送单详情浮窗
    const getDeliveryInfo = (deliveryId) => {
      const order = rawData.value.find(order => order.deliveryId === deliveryId);
      if (!order) return '未找到配送单详情';

      return `
    配送单ID: ${order.deliveryId}
    状态: ${order.state1}
    总重量: ${order.weight}${order.weightUnit}
    创建时间: ${formatDate(order.generatedDate1)}
  `;
    };

    const resetFilters = () => {
      filters.deliveryId = "";
      filters.origin = "";
      filters.generatedDate = [];
      filters.state = null;
      filters.vehicleNumber = "";
      filters.deliveryType = null;
      currentPage.value = 1;
      search();
    };

    const handleCurrentChange = (page) => {
      currentPage.value = page;
      search();
    };

    const openDialog = (row, isEdit) => {
      // 打开修改对话框逻辑
      if (isEdit) {
        console.log(row);
        form.deliveryId = row.deliveryId;
        form.deliveryBatchId = row.deliveryBatchId;
        form.state = row.state;
        form.weight = row.weight;
        form.weightUnit = row.weightUnit;
        form.vehicleNumber = row.vehicleNumber;
        editDialogVisible.value = true;
        console.log(form)
      }
    };

    const submitEdit = async () => {
      try {
        const response = await updateDelivery(form);
        ElMessage.success("更新成功");
        editDialogVisible.value = false;
        await search(); // 刷新数据
      } catch (error) {
        ElMessage.error("更新失败");
      }
    };

    const resetForm = () => {
      Object.keys(form).forEach(key => form[key] = '');
    };


    const selectedDeliveries = ref([]);
    // 表格主选择框选中时触发
    const handleSelectionChange = (rows) => {
      selectedDeliveries.value = rows;
    };

    const detailDialogVisible = ref(false);
    const logisticDialogVisible = ref(false);

    const openDetailDialog = async (deliveryBatchId) => {
      try {
        selectedDelivery.value = deliveryBatchId; // 设置选中的配送单数据
        detailDialogVisible.value = true;  // 打开详情弹窗
        console.log(detailDialogVisible.value);
        console.log(deliveryBatchId);

      } catch (error) {
        ElMessage.error('获取配送单详情失败');
      }
    };

    const closeDetailDialog = () => {
      detailDialogVisible.value = false;
      selectedDelivery.value = {}; // 清空选中的数据
    };

    const openLogisticDialog = async (delivery) => {
      try {
        selectedDelivery.value = delivery; // 设置选中的配送单数据
        logisticDialogVisible.value = true;
        console.log(logisticDialogVisible.value);

      } catch (error) {
        ElMessage.error('获取物流信息失败');
      }
    };

    const closeLogisticDialog = () => {
      logisticDialogVisible.value = false;
      selectedDelivery.value = {}; // 清空选中的数据
    };

    const handleDelete = async (row) => {
      try {
        await deleteDelivery(row.deliveryOrderId);
        search();
      } catch (error) {
        ElMessage.error("删除失败");
      }
    };

    const formatDate = (value) => {
      if (!value) return '';
      const date = new Date(value);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    };

    onMounted(() => {
      search();
    });

    return {
      filters,
      currentTableData,
      total,
      pageSize,
      currentPage,
      search,
      resetFilters,
      handleCurrentChange,
      openDialog,
      handleDelete,
      formatDate,
      openDetailDialog,
      detailDialogVisible,
      selectedDeliveries,
      closeDetailDialog,
      selectedDelivery,
      handleSelectionChange,
      openLogisticDialog,
      logisticDialogVisible,
      closeLogisticDialog,
      editDialogVisible,
      form,
      submitEdit,
      resetForm,
      getDeliveryInfo,
    };
  },
};
</script>

<style scoped>
.el-container {
  height: 100%;
  width: 100%;
}

.content-wrapper {
  background-color: #f5f7fa;
  min-height: inherit;
  display: flex;
  height: calc(100vh - 84px);
}

.content-container {
  background-color: white;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);
  width: calc(100% - 40px);
  height: calc(100vh - 84px - 30px);
  box-sizing: border-box;
  border-radius: 8px;
  position: relative;
  display: flex;
  flex-direction: column;
  margin-left: 20px;
  margin-top: 15px;
}

.divider {
  height: 1px;
  background-color: #eaeaea;
  margin-top: 0;
  margin-bottom: 12px;
}

.dialog-footer {
  float:right;
}

.action-buttons {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
}

.right-aligned {
  display: flex;
  justify-content: flex-end;
}

.el-segmented {
  width: 100%;
}

.el-form-item.right:deep(.el-form-item__content) {
  justify-content: end;
}

.demo-form-inline {
  display: flex;
  flex-wrap: wrap;
  background: white;
}

.full-width {
  width: 100%;
}

.fixed-pagination {
  position: relative;
  right: 0;
  align-self: end;
  margin-top: 20px;
}

.dialog-footer {
  text-align: right;
}

</style>
